from typing import Dict
from PySide2.QtWidgets import QWidget, QLabel, QSlider, QPushButton, QComboBox, QFileDialog, QLineEdit
from src.LogPlayer.components.Player import Player, STATE


class PlayControl:
    lblStartTime: QLabel
    lblEndTime: QLabel
    lblCurrentTime: QLabel
    btnPlayPause: QPushButton
    btnChooseFile: QPushButton
    sldSeek: QSlider
    cmbSpeed: QComboBox
    txtFilePath: QLineEdit

    renderedCallbacks: Dict[int, callable] = {}

    def __init__(self, root: QWidget):
        self.root = root
        self._initUi()
        self.player = Player()

    def _initUi(self):
        self.lblStartTime = self.root.lbl_start_time
        self.lblEndTime = self.root.lbl_end_time
        self.lblCurrentTime = self.root.lbl_current_time
        self.btnPlayPause = self.root.btn_play_pause
        self.btnChooseFile = self.root.btn_choose_file
        self.sldSeek = self.root.sld_seek
        self.cmbSpeed = self.root.sld_seek
        self.txtFilePath = self.root.txt_file_path

        self.btnChooseFile.clicked.connect(self._selectFile)
        self.btnPlayPause.clicked.connect(self._playPause)

    def _selectFile(self):
        self.btnPlayPause.setDisabled(True)
        fileName = QFileDialog.getOpenFileName(self.root, '选择log文件', '../../samples')[0]
        print('selected log file:' + fileName)
        self.txtFilePath.setText(fileName)
        self.player.reset()
        self.player.setDataSource(fileName)
        def onPreparedListener():
            print('prepered 111')
            self.btnPlayPause.setText('播放')
            self.btnPlayPause.setDisabled(False)
            for type in self.renderedCallbacks:
                self.player.setWindow(type, self.renderedCallbacks[type])
        self.player.setOnPreparedListener(onPreparedListener)
        self.player.prepare()

    def _playPause(self):
        state = self.player.getCurrentState()
        if state == STATE.STARTED:
            self.player.pause()
            self.btnPlayPause.setText('播放')
        else:
            self.player.play()
            self.btnPlayPause.setText('暂停')


    def _play(self):
        if self.player.getCurrentState() == STATE.STARTED:
            self.player.pause()
            self.btnPlayPause.setText('播放')
        elif self.player.getCurrentState() in [STATE.PREPARED, STATE.PAUSED, STATE.STOPPED, STATE.PLAYBACK_COMPLETED]:
            self.player.play()
            self.btnPlayPause.setText('暂停')


    def setWindow(self, type: int, callback: callable):
        self.renderedCallbacks[type] = callback
